<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/10/17
 * Time: 18:26
 */

namespace app\admin\model;


use think\Db;
use think\Exception;
use think\Model;

/**
 * Class SysAdminMenu
 * @package app\admin\model
 *
 * @property integer id
 * @property string link
 * @property string title
 * @property string theme
 * @property integer parent_id
 * @property integer rank
 */
class SysAdminMenu extends Model
{
    protected $table = 'sys_admin_menu';
    protected $pk = 'id';

    private static $SaveFields = [
        'link',
        'title',
        'theme',
        'parent_id',
        'rank',
    ];
    public static function getSaveFields(): array {
        return self::$SaveFields;
    }

    public static function create($data = [], $field = null)
    {
        $sql = <<<SQL
SELECT max(id) max_id FROM sys_admin_menu
SQL;
        $re = Db::query($sql);
        $id = ($re[0]['max_id'] ?? 0) + 1;
        $fields = '';
        $params = '';
        foreach ($data as $k => $v) {
            if (in_array($k, self::$SaveFields) == false) unset($data[$k]);
            else {
                $fields .= ', '.$k;
                $params .= ', :'.$k;
            }
        }
        $sql = <<<SQL
INSERT INTO sys_admin_menu (id $fields) VALUES 
(:id $params)
SQL;
        $data['id'] = $id;
        Db::execute($sql, $data);
        return self::get($id); // TODO: Change the autogenerated stub
    }

    /**
     * 获取菜单树
     *
     * @return mixed
     */
    public static function menuAllTree() {

        $sql = <<<SQL
SELECT * FROM sys_admin_menu WHERE parent_id=:pid ORDER BY rank ASC,id DESC 
SQL;
        $list = Db::query($sql, ['pid' => 0]);
        foreach ($list as & $item) {
            $item['children'] = Db::query($sql, ['pid' => $item['id']]);
        }

        return $list;
    }

    /**
     * 返回角色的菜单树
     *
     * @param int $role_id
     * @return array
     */
    public static function menuTree(int $role_id) {

        $sql = <<<SQL
SELECT m.* 
FROM sys_admin_menu m JOIN sys_role_menu rm ON m.id = rm.menu_id
WHERE rm.role_id=:role_id
ORDER BY m.rank ASC,m.id DESC 
SQL;
        $results = Db::query($sql, ['role_id' => $role_id]);

        $list = [];
        foreach ($results as $result) {
            if ($result['parent_id'] == 0) $list[] = $result;
        }
        foreach ($list as & $item) {
            $children = [];
            foreach ($results as $result) {
                if ($result['parent_id'] == $item['id']) $children[] = $result;
            }
            $item['children'] = $children;
        }

        return $list;
    }

    /**
     * 保存角色菜单
     *
     * @param int $role_id
     * @param array $menu_tree
     * @throws Exception
     */
    public static function saveMenu(int $role_id, array $menu_tree) {

        try{
            Db::startTrans();

            $sql = 'DELETE FROM sys_role_menu WHERE role_id=:role_id';
            Db::execute($sql, ['role_id' => $role_id]);

            $sql = <<<SQL
INSERT INTO sys_role_menu (role_id, menu_id) VALUES (:role_id, :menu_id)
SQL;
            foreach ($menu_tree as $menu) {
                Db::execute($sql, ['role_id' => $role_id, 'menu_id' => $menu]);
            }

            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            throw $exception;
        }
    }

}